import {
  Avatar,
  List,
  NavBar,
  Button,
  Modal,
  Form, Input, Toast
} from 'antd-mobile';
import {
  CheckShieldOutline,
  EyeInvisibleOutline, EyeOutline
} from 'antd-mobile-icons';
import styles from './index.less';
import { useState, useEffect } from 'react';
import QRCode from 'qrcode'
import { getQrcode, getUserFn, login } from './server'

export const Account = () => {
  const [qrcodeImg, setQrcodeImg] = useState<string>('');
  const [state, setState] = useState({
    restaurant_name: '',
    restaurant_type: '',
    cuisine_type: '',
    address: '',
  });
  const [visible, setVisible] = useState(false)

  const onFinish = async (values: any) => {
    const msg = await login({ ...values });
    if (msg.access_token) {
      Toast.show({
        icon: 'success',
        content: '保存成功',
      })
      window.localStorage.setItem('token', `${msg.token_type} ${msg.access_token}`);
      window.location.reload();
      return;
    } else {
      Toast.show({
        icon: 'fail',
        content: msg.detail,
      });
    }
  }

  const getList = () => {
    getUserFn().then((res: any) => {
      // const token = localStorage.getItem('token');
      if (res) {
        setState({
          restaurant_name: res.restaurant_name,
          restaurant_type: res.restaurant_type,
          cuisine_type: res.cuisine_type,
          address: res.address,
        })
      }
    })
  }

  const getAuth = () => {
    const token = localStorage.getItem('token');
    if (!token) {
      return
    } else {
      // getList()
    }
  }

  const openUrl = () => {
    const token = localStorage.getItem('token');
    getQrcode(token).then((res: any) => {
      const url = `http://47.108.248.39/dist/index.html?api_key=${res.api_key}`
      QRCode.toDataURL(url).then((imgUrl: string) => {
        setQrcodeImg(imgUrl)
        Modal.alert({
          title: 'key获取',
          content: <div style={{ width: '100%', height: '100%', display: 'flex', justifyContent: 'center' }}>
            <img src={imgUrl} alt="" style={{ width: '100px', height: '100px' }} />
          </div>,
          showCloseButton: true,
          confirmText: '关闭', // 刷新
          onConfirm: () => {
            console.log('Confirmed')
          },
        })
      }).catch((err: Error) => {
        console.log(err)
      })
    })
  }

  useEffect(() => {
    getAuth()
  }, []);

  const listData = [
    [
      {
        title: '店铺名称', // restaurant_name
        extra: state.restaurant_name,
      },
      {
        title: '店铺类型', //restaurant_type
        extra: state.restaurant_type,
      },
      {
        title: '美食类型', //cuisine_type
        extra: state.cuisine_type,
      },
      {
        title: '门店地址', // address
        extra: state.address,
      },
      {
        icon: <CheckShieldOutline className="icon-1" />,
        title: 'key获取',
        clickable: true,
        extra: <Button
          block
          onClick={openUrl}
        >
          获取
        </Button>,
      },
    ],
  ];

  return (
    <div className={styles.account}>
      {
        window.localStorage.getItem('token') ? (
          <>
            <NavBar
              back={null}
              left={<span className={styles.leftTitle}>我的</span>}
            />
            <div className={styles.body}>
              <div className={styles.headerWarp}>
                <List>
                  <List.Item
                    prefix={<Avatar src='' />}
                  >
                    用户
                  </List.Item>
                </List>
              </div>
            </div>
            {listData.map((group, i) => {
              return (
                <div className={styles.listGroupWarp} key={`list-group-${i}`}>
                  <List mode="card">
                    {group.map((item, j) => (
                      <List.Item
                        key={`list-item-${i}-${j}`}
                        prefix={item.icon}
                        clickable={item.clickable}
                        extra={item.extra}
                      >
                        {item.title}
                      </List.Item>
                    ))}
                  </List>
                </div>
              );
            })}
          </>
        ) : (
          <div className={styles['login-page-wrap']}>
            <div className={styles.title}>内容管理</div>
            <Form
              layout='horizontal'
              onFinish={onFinish}
              footer={
                <Button block type='submit' color='primary' size='large'>
                  提交
                </Button>
              }
            >
              <Form.Item
                name='account'
                label='姓名'
                rules={[{ required: true, message: '姓名不能为空' }]}
              >
                <Input placeholder='请输入姓名' />
              </Form.Item>
              <Form.Item
                name='password'
                label='密码'
                rules={[{ required: true, message: '密码不能为空' }]}
              >
                <div className={styles.password}>
                  <Input
                    className={styles.input}
                    placeholder='请输入密码'
                    type={visible ? 'text' : 'password'}
                  />
                  <div className={styles.eye}>
                    {!visible ? (
                      <EyeInvisibleOutline onClick={() => setVisible(true)} />
                    ) : (
                      <EyeOutline onClick={() => setVisible(false)} />
                    )}
                  </div>
                </div>
              </Form.Item>
            </Form>
          </div>
        )
      }
    </div>
  );
};


export default Account